﻿using Microsoft.IdentityModel.Claims;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Claims;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CNRSccp.Claims.Helper
{
    public class ClaimsHelper_mas
    {
        /// <summary>
        /// Check if claim user exists and if not create it
        /// WARNING : Site.AllowUnsafeUpdates must be set at true before using this method
        /// </summary>
        /// <param name="web">web</param>
        /// <param name="userLoginName">login Name not claim encoded</param>
        /// <param name="userLoginEmail">login Email</param>
        /// <param name="typeOfClaims">type of claim we want to encode (ex : SPClaimTypes.UserLogonName)</param>
        /// <returns></returns>
        //public static SPUser EnsureClaimUser(SPWeb web, string userLoginName, string userLoginEmail, string typeOfClaims)
        //{
        //    try
        //    {
        //        SPClaimProviderManager claimManager = new SPClaimProviderManager();

        //        //SPClaim claim = new SPClaim(typeOfClaims, userLoginName, ClaimValueTypes.String, "TrustedProvider:" + ContextHelper.GetADFSReference(web));
        //        SPClaim claim = new SPClaim(typeOfClaims, userLoginName, ClaimValueTypes.String, SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, ClaimsParameters.Instance.ADFSReference));

        //        string claimUserName = claimManager.EncodeClaim(claim);

        //        if (!SharepointSecurityHelper.IsUserExist(web.SiteUsers, claimUserName))
        //            web.SiteUsers.Add(claimUserName, userLoginEmail, userLoginName, userLoginName);

        //        SPUser user = web.SiteUsers[claimUserName];
        //        user.Name = userLoginName;
        //        user.Email = userLoginEmail;
        //        user.Notes = userLoginName;
        //        user.Update();

        //        return user;
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.Write(ex.Message);
        //        LogHelper.Log(LogCategorie.ClaimsHelper, "error in EnsureClaimUser : " + ex.Message, TraceSeverity.Unexpected);
        //        return null;
        //    }
        //}

        /// <summary>
        /// Remove claim information from an user or role
        /// ex : i:05.t|mgiadfs.aresu.dsi.cnrs.fr|jean-marie.thia@dsi.cnrs.fr => jean-marie.thia@dsi.cnrs.fr
        /// </summary>
        /// <param name="encodedClaim">Encoded claim</param>
        /// <param name="force">if true, return a value even if it wasn't a claim</param>
        /// <returns>Decoded claim</returns>
        public static string GetDecodedClaim(string encodedClaim, bool force)
        {
            string userName = string.Empty;

            if (encodedClaim.Contains("0#.w"))
            {
                string[] strArr = encodedClaim.Split('|');
                userName = strArr[1];
            }
            else
            {
                int userPipe = encodedClaim.LastIndexOf("|");
                if (userPipe > -1)
                    userName = encodedClaim.Substring(userPipe + 1);
                else if (force)
                    userName = encodedClaim;
            }

            return userName;
        }

        public static bool CheckEmail(string email)
        {
            if (String.IsNullOrEmpty(email))
                return false;

            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                  @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                  @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
            Regex regex = new Regex(strRegex);
            if (regex.IsMatch(email))
                return true;
            else
                return false;
        }

        #region Logs ULS
        public static void LogToULS(string message, TraceSeverity traceSeverity, EventSeverity eventSeverity)
        {
            try
            {
                SPDiagnosticsCategory category = new SPDiagnosticsCategory("CNRSClaimProvider", traceSeverity, eventSeverity);
                SPDiagnosticsService ds = SPDiagnosticsService.Local;
                ds.WriteTrace(0, category, traceSeverity, message);
            }
            catch
            {
            }
        }
        #endregion

    }
}
